import datetime
import pymysql
import redis
from constant.constant import *
from globals.globals import *

with my_session() as session:
    # 电表tag
    electric_sql = 'select * from equipmenttag where tag_means = "电量"'
    electric_tags = session.execute(electric_sql).fetchall()

    # 水表tag
    water_sql = 'select * from equipmenttag where tag_means = "饮用水流量"'
    water_tags = session.execute(water_sql).fetchall()

    # 汽表tag
    steam_sql = 'select * from equipmenttag where tag_means = "蒸汽流量"'
    steam_tags = session.execute(steam_sql).fetchall()

    # 电价
    elec_price_sql = 'select * from electricprice'
    elec_prices = session.execute(elec_price_sql).fetchall()
    # 水汽价
    water_steam_sql = 'select * from watersteamprice'
    water_steam_prices = session.execute(water_steam_sql).fetchall()


pool = redis.ConnectionPool(host=constant.REDIS_HOST, port=constant.REDIS_PORT,password=constant.REDIS_PASSWORD, decode_responses=True)
r = redis.Redis(connection_pool=pool)


class Increment():
    '''增量模型'''
    def increment_count(self, models):
        '''增量计算'''
        for model in models:
            value_now = float(r.hget('data_realtime', model.tag_id)) if r.hget('data_realtime', model.tag_id) != 'init' and r.hget('data_realtime', model.tag_id)  else None
            value_last = float(r.hget('data_realtime', model.tag_id + '_last')) if r.hget('data_realtime', model.tag_id + '_last') != 'init' and r.hget('data_realtime', model.tag_id + '_last') else None
            if not value_last:
                if value_now:
                    r.hset('data_realtime', model.tag_id + '_last', value_now)
            else:
                if value_now:
                    r.hset('data_realtime', model.tag_id + '_last', value_now)
                    increment = float(r.hget('data_realtime', model.tag_id + '_incre')) if r.hget('data_realtime', model.tag_id + '_incre') else None
                    if not increment:
                        r.hset('data_realtime', model.tag_id + '_incre', value_now - value_last) if value_now >= value_last else None
                    else:
                        r.hset('data_realtime', model.tag_id + '_incre', increment + value_now - value_last) if value_now >= value_last else None

    def increment_insert(self, models):
        '''增量写入'''
        if models:
            start_time = datetime.datetime.now()
            hour_min = start_time.strftime("%H:%M")
            # 单价处理
            price_id = None
            if models[0].tag_means == '饮用水流量':
                for item in water_steam_prices:
                    if item.PriceType == '饮用水':
                        price_id = item.ID
            elif models[0].tag_means == '电量':
                for elec_price in elec_prices:
                    if hour_min > elec_price.StartTime and hour_min <= elec_price.EndTime:
                        price_id = elec_price.ID
                        break
            elif models[0].tag_means == '蒸汽流量':
                for item in water_steam_prices:
                    if item.PriceType == '汽':
                        price_id = item.ID
            # sql组装
            sql = f'insert into {models[0].insert_table} values '
            for model in models:
                increment = float(r.hget('data_realtime', model.tag_id + '_incre')) if r.hget('data_realtime',model.tag_id + '_incre') else None
                increment = round((increment) / model.devide_by, 1) if increment else 0
                r.hset('data_realtime', model.tag_id + '_incre', 0)
                sql += f'(null,"{model.tag_id}", {increment}, "{model.unit}", {price_id}, "{start_time.strftime("%Y-%m-%d %H:%M")}", ' \
                       f'"{start_time.strftime("%Y")}", "{start_time.strftime("%Y-%m")}", "{start_time.strftime("%Y-%m-%d")}", "{start_time.strftime("%Y-%m-%d %H")}"),'
            sql = sql[:-1]
            with my_session() as session:
                session.execute(sql)

def increment_electric_job():
    '''电增量更新'''
    Increment().increment_count(electric_tags)
def insert_elec_increment():
    '''电增量写入'''
    Increment().increment_insert(electric_tags)

def increment_water_job():
    '''水增量更新'''
    Increment().increment_count(water_tags)
def insert_water_increment():
    '''水增量写入'''
    Increment().increment_insert(water_tags)

def increment_steam_job():
    '''汽增量更新'''
    Increment().increment_count(steam_tags)
def insert_steam_increment():
    '''汽增量写入'''
    Increment.increment_insert(steam_tags)





